package com.swt.gap.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.swt.gap.common.PageResult;
import com.swt.gap.common.PermissionService;
import com.swt.gap.dao.FileDao;
import com.swt.gap.model.entity.File;
import com.swt.gap.model.entity.Task;
import com.swt.gap.model.vo.resourcecenter.DataListVO;
import com.swt.gap.model.vo.resourcecenter.DataPassword;
import com.swt.gap.model.vo.resourcecenter.DataResourceStatistics;
import com.swt.gap.service.DataResourceService;
import com.swt.gap.service.SysGroupService;
import com.swt.gap.util.UserLoginUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class DataResourceServiceImpl implements DataResourceService {

    private final FileDao fileDao;
    private final SysGroupService sysGroupService;
    private final PermissionService permissionService;

    public DataResourceServiceImpl(FileDao fileDao, SysGroupService sysGroupService, PermissionService permissionService) {
        this.fileDao = fileDao;
        this.sysGroupService = sysGroupService;
        this.permissionService = permissionService;
    }

    @Override
    public PageResult<DataListVO> listDataResources(String keyword, Integer fileClassId,
                                                    Integer pageNum, Integer pageSize,
                                                    Boolean isOwnCreated, Boolean hasPassword) {
        List<Integer> userIds = new ArrayList<>();
        Integer loginUserId = UserLoginUtils.getUserId();
        if (null == isOwnCreated) {
            userIds.addAll(sysGroupService.listSameGroupUserByUserId(loginUserId));
        } else if (isOwnCreated) {
            userIds.add(loginUserId);
        } else {
            for (Integer userId : sysGroupService.listSameGroupUserByUserId(loginUserId)) {
                if (!userId.equals(loginUserId)) {
                    userIds.add(userId);
                }
            }
        }
        Page<DataListVO> res = new Page<>();
        if (!userIds.isEmpty()) {
            if (null == pageNum || pageNum < 1) {
                pageNum = 1;
            }
            if (null == pageSize || pageSize < 1) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNum, pageSize);
            res = fileDao.selectByNameAndClassIdAndCreator(keyword, fileClassId, userIds, hasPassword);
            res.getResult().forEach(data -> {
                data.setHasReadPermission(permissionService.hasReadPerm(loginUserId, data.getCreatedBy(), data.getPassword()));
                data.setHasWritePermission(permissionService.hasWritePerm(loginUserId, data.getCreatedBy()));
                data.setHasPassword(!StringUtils.isEmpty(data.getPassword()));
                data.setPassword("");
            });
        }
        return new PageResult<>(res);
    }

    @Override
    public Integer updateDataPassword(DataPassword dataPassword) {
        if (!StringUtils.isEmpty(dataPassword.getPassword())) {
            dataPassword.setPassword(SecureUtil.md5(dataPassword.getPassword()));
        }
        return fileDao.updatePassword(dataPassword.getPassword(), dataPassword.getFileIds());
    }

    @Override
    public Boolean getReadPerm(Integer fileId, String password) {
        boolean isSuccess;
        Integer userId = UserLoginUtils.getUserId();
        File file = fileDao.selectByPrimaryKey(fileId);
        if(null != file) {
            if (permissionService.hasReadPerm(userId, file.getCreatedBy(), file.getPassword())) {
                isSuccess = true;
            } else {
                String inputPassword = SecureUtil.md5(password);
                isSuccess = inputPassword.equals(file.getPassword());
            }
        } else {
            isSuccess = false;
        }
        return isSuccess;
    }

    @Override
    public Boolean hasWritePermission(Integer userId, Integer fileId) {
        boolean retValue = false;
        File file = fileDao.selectByPrimaryKey(fileId);
        if (null != file && null != file.getCreatedBy()) {
            retValue = permissionService.hasWritePerm(userId, file.getCreatedBy());
        }
        return retValue;
    }

    @Override
    public DataResourceStatistics getStatistics(Integer fileClassId) {
        Integer ownCreatedCount = listDataResources(null, fileClassId, null, null, true,
                null).getTotalRecord();
        Integer passwordCount = listDataResources(null, fileClassId, null, null, null,
                true).getTotalRecord();
        Integer noPasswordCount = listDataResources(null, fileClassId, null, null, null,
                false).getTotalRecord();
        return  DataResourceStatistics.builder()
                .ownCreatedCount(ownCreatedCount)
                .passwordCount(passwordCount)
                .noPasswordCount(noPasswordCount)
                .build();
    }
}
